package com.dx.as.db;

import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.os.AsyncTask;
import com.dx.as.common.CommonUtils;
import com.dx.as.common.log.LogUtil;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jwaoo on 2017/6/9.
 */

public class SqlLiteHelper <T extends RoomDatabase>{
    private static SqlLiteHelper sInstance;
    private Map<Class<T>,RoomDatabase> databaseMap = new HashMap<>();
    private static final Object LOCK = new Object();
    static Context mContext;
    public synchronized static SqlLiteHelper getInstance(Context context) {
        if (sInstance == null) {
            synchronized (LOCK) {
                if (sInstance == null) {
                    sInstance = new SqlLiteHelper();
                }
            }
        }
        mContext = context;
        return sInstance;
    }

    public void createDB(final Class<T> tClass , final IDBListener listener , final boolean needSpt){

        new AsyncTask<Context, Void, Void>() {
            @Override
            protected Void doInBackground(Context... params) {
                try {
                    String key = getDBName(tClass,needSpt);
                    databaseMap.put(tClass,Room.databaseBuilder(mContext,tClass, key).build());
                    listener.onOption(databaseMap.get(tClass));
                }catch (Exception ex){
                    ex.printStackTrace();
                    LogUtil.d("db create error",ex.toString());
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void ignored) {
            }
        }.execute(mContext.getApplicationContext());
    }

    public void dbOption(final Class<T> tClass ,final IDBListener listener) {
        this.dbOption(tClass,listener,false);
    }

    public void dbOption(final Class<T> tClass ,final IDBListener listener,boolean needSpt) {
        final RoomDatabase database = databaseMap.get(tClass);

        if (database == null){
            createDB(tClass,listener,needSpt);
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                listener.onOption(database);
            }
        }).start();
    }

    public void closeDb(Class<T> tClass,boolean needSpt){
        databaseMap.remove(tClass);
    }

    private String getDBName(Class<T> tClass,boolean needSpt){
        if (!needSpt) return tClass.getSimpleName();
        int iMAccount = CommonUtils.getIMAccount();
        return iMAccount > 0 ? iMAccount+"_"+tClass.getSimpleName() : "";
    }
}
